<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Models\Cabinet;
use App\Models\CabinetPoint;
use App\Models\CabinetAlarmLog;
use App\Models\CabinetData;
use App\Models\CabinetDataSecond;
use Dcat\Admin\Layout\Content;
use Illuminate\Support\Facades\DB;
use App\Handlers\WeconHandler;
use Illuminate\Support\Collection;
use Dcat\Admin\Admin;
use Dcat\Admin\Layout\Row;

class CabinetChildrenController extends Controller
{
    public function index(Content $content, $pid){
        Admin::script(
            <<<JS
    var table = document.getElementById('grid-table');
    table.style.cssText="background-color:#e3e5eb;"
JS            
        );
        return $content
            ->body(headmenu($pid))
            ->body(function (Row $row) use($pid) {
                $cabinets = Cabinet::find($pid);
                $getWeekCollectData = $this->getWeekCollect($pid);
                $getTotalAlarmData = $this->getTotalAlarm($pid);
                $row->column(8, view('admin.card.weekCollect', $getWeekCollectData));
                $row->column(4, view('admin.card.totalAlarm', $getTotalAlarmData));
            })
            ->body($this->grid($pid));
    } 
    
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid($pid)
    {
        $m = Cabinet::where('pid', $pid);

        return Grid::make($m, function (Grid $grid) use ($pid) {
            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->display(function($name) {
                $hasLog = CabinetAlarmLog::where('cabinet_id', $this->id)->where('status', CabinetAlarmLog::STATUS_NO)->first();
                if ($hasLog) {
                    return '<span style="color: red">'.$name.'</span>';
                } else {
                    return $name;
                }
                error_log("id = ".print_r($this->id,1)."\n",3,'/tmp/joker.log');
                return $name;
            });
            $grid->column('show', '是否显示')->using(Cabinet::SHOW_TEXT);
            // $grid->column('name','名称');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            $grid->disableCreateButton();
            $grid->disableRefreshButton();
            $parent = Cabinet::find($pid);
        });
    }

    public function show($pid, $id, Content $content)
    {
        $parent = Cabinet::find($pid);
        $self = Cabinet::find($id);
        return $content
            ->translation($self['name'])
            ->title($self['name'])
            ->description($parent['name'])
            ->body($this->detail($id));
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Cabinet(), function (Show $show) {
            $show->field('id', 'ID');
            $show->field('name','名称');

            $show->relation('points', '采集点', function ($model) {
                $grid = new Grid(new CabinetPoint);
                $grid->model()->where('cabinet_id', $model->id);
                // 设置路由
                $grid->setResource('points');
                $grid->column('id', '采集点 Id');
                $grid->column('alias', '采集点编号')->display(function ($alias) {
                    return str_replace('a_', '', $alias);
                });
                $grid->column('name', '采集点名称');
                $grid->disableRefreshButton();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disableActions();
                // $grid->disablePerPages();
                // $grid->simplePaginate(false);
                return $grid;
            });

            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    public function edit($pid, $id, Content $content)
    {
        $parent = Cabinet::find($pid);
        $self = Cabinet::find($id);
        return $content
            ->translation($self['name'])
            ->title($self['name'])
            ->description($parent['name'])
            ->body($this->form($pid)->edit($id));
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($pid = 0)
    {
        $builder = Cabinet::with('points');
        return Form::make($builder, function (Form $form) use ($pid) {
            $form->tab('基础信息', function (Form $form) use ($pid) {
                $form->display('id');
                $form->text('name', '名称')->required();
                $form->radio('show', '是否显示')
                    ->options(Cabinet::SHOW_TEXT)
                    ->default(1, true);
                $form->hidden('pid')->value($pid);
                $form->color('color', '采集点显示颜色');
                $form->display('created_at');
                $form->display('updated_at');
            })->tab('采集点信息设置', function (Form $form) {
                $form->hasMany('points', '采集点', function (Form\NestedForm $form) {
                    $form->text('alias', '采集点编号')->customFormat(function ($alias) {
                        return str_replace('a_', '', $alias);
                    })->required();
                    $form->text('name', '采集点名称')->required();
                    $form->text('units', '单位');
                    $form->text('decimal', '小数位');

                    $form->radio('writable', '是否可写')
                    ->options(CabinetPoint::WRITABLE_TEXT)
                    ->default(0, true);

                    $form->radio('realtime_show', '实时数据中显示')
                    ->options(['1' => '是', '0' => '否'])
                    ->default(1, true);
                    $form->radio('history_show', '历史记录中显示')
                    ->options(['1' => '是', '0' => '否'])
                    ->default(1, true);
                    $form->radio('history_line_show', '历史曲线中显示')
                    ->options(['1' => '是', '0' => '否'])
                    ->default(1, true);
                });
            });

            $form->deleted(function (Form $form, $result) {
                if ($result) {
                    $data = $form->model()->toArray();
                    Cabinet::afterDeletedCabinet($data[0]['id'], $data[0]['box_id'], $data[0]['group_id']);
                }
            });

        });
    }

    public function update($pid, $id)
    {
        return $this->form()->update($id);
    }

    public function destroy($pid, $id)
    {
        return $this->form()->destroy($id);
    }

    protected function getWeekCollect($pid){
        $cabinets = Cabinet::where('pid', $pid)->where('show', Cabinet::SHOW_YES)->get()->toArray();

        $firstDay = date("Y-m-d", strtotime("-6 days"));
        for ($i=0; $i < 7; $i++) {
            $xData[] = date("m-d", strtotime("$firstDay +$i days"));
            $day = date("Y-m-d", strtotime("$firstDay +$i days"));

            $start = strtotime($day.' 00:00:00');

            if ($i == 6) {  //today
                $end = time();
            } else {
                $end = strtotime($day.' 23:59:59');
            } 

            foreach ($cabinets as $oneCabinet) {
                // $num = CabinetDataSecond::getCount($oneCabinet['id'], $start, $end);
                $num = rand(0,100);
                $cabinetId = $oneCabinet['id'];
                $$cabinetId[] = $num;
            }
        }

        $legend = [];
        $series = [];
        foreach ($cabinets as $oneCabinet) {
            $legend[] = $oneCabinet['name'];
            $oneSeries['name'] = $oneCabinet['name'];
            $oneSeries['type'] = 'line';
            $cabinetId = $oneCabinet['id'];
            $oneSeries['data'] = $$cabinetId;
            array_push($series, $oneSeries);
        }

        $data['legend'] = json_encode($legend);
        $data['series'] = json_encode($series);
        $data['xData'] = json_encode($xData);
        // error_log("xData = ".print_r($xData,1)."\n",3,'/tmp/joker.log');
        return $data;
    }

    protected function getTotalAlarm($pid){
        // $dealAlarm = CabinetAlarmLog::where('cabinet_pid', $pid)->where('status', CabinetAlarmLog::STATUS_YES)->count();
        $dealAlarm = rand(0,100);
        // $undealAlarm = CabinetAlarmLog::where('cabinet_pid', $pid)->where('status', CabinetAlarmLog::STATUS_NO)->count();
        $undealAlarm = 100 - $dealAlarm;
        
        $alarmData = [
            ['value' => $dealAlarm, 'name' => '已处理'],
            ['value' => $undealAlarm, 'name' => '未处理']
        ];
        $data['alarmData'] = json_encode($alarmData);
        return $data;
    }
}
